package com.git.contractmanagement.controller;

import cn.dev33.satoken.stp.StpUtil;

import com.git.contractmanagement.entity.Contract;
import com.git.contractmanagement.entity.UserFavorite;
import com.git.contractmanagement.exception.BusinessException;
import com.git.contractmanagement.repository.ContractRepository;
import com.git.contractmanagement.repository.UserFavoriteRepository;
import com.git.contractmanagement.service.impl.ContractService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.*;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/contracts")
@CrossOrigin
public class ContractController {

    @Autowired
    private ContractService contractService;

    @Autowired
    private ContractRepository contractRepository;

    @Autowired
    private UserFavoriteRepository userFavoriteRepository;

    @Value("${file.server-url}")
    private String fileServerUrl;

    // 新建合同
    @PostMapping
    public ResponseEntity<Contract> createContract(@RequestBody Contract contract) {
        if (contract.getUploadTime() == null) {
            contract.setUploadTime(LocalDateTime.now());
        }
        Contract updatedContract = contractService.createContract(contract);
        return ResponseEntity.ok(updatedContract);
    }

    // 根据ID查询单个合同
    @GetMapping("/{id}")
    public ResponseEntity<Contract> getContractById(@PathVariable Integer id) {
        return contractService.getById(id).map(contract -> {
            convertLocalPathsToHttpUrls(contract);
            return ResponseEntity.ok(contract);
        }).orElseGet(() -> ResponseEntity.notFound().build());
    }

    // 删除合同
    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteContract(@PathVariable Integer id) {
        try {
            contractService.deleteContract(id);
            return ResponseEntity.noContent().build(); // 204
        } catch (IllegalArgumentException e) {
            System.err.println("参数错误: " + e.getMessage());
            return ResponseEntity.badRequest().build(); // 400
        } catch (RuntimeException e) {
            System.err.println("业务异常: " + e.getMessage());
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).header("X-Error", e.getMessage()).build();
        } catch (Exception e) {
            System.err.println("未知异常: " + e.getMessage());
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

    // 编辑合同
    @PutMapping("/{id}")
    public ResponseEntity<Contract> updateContract(@PathVariable Integer id, @RequestBody Contract contractDetails) {
        Contract updatedContract = contractService.updateContract(id, contractDetails);
        return ResponseEntity.ok(updatedContract);
    }

    // 查询合同（分页、关键字、分类、排序）
    @GetMapping
    public ResponseEntity<Page<Contract>> getContracts(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) String category,
            @RequestParam(defaultValue = "uploadTime") String sortBy,
            @RequestParam(defaultValue = "desc") String direction) {

        Sort.Direction sortDirection = direction.equalsIgnoreCase("asc") ? Sort.Direction.ASC : Sort.Direction.DESC;
        Pageable pageable = PageRequest.of(page, size, Sort.by(sortDirection, sortBy));

        Page<Contract> contracts = (Page<Contract>) contractService.searchContracts(keyword, category, pageable);
        System.out.println("Contracts from service: " + contracts.getContent().size() + " items");

        // 确保转换所有合同的路径为HTTP URL
        Page<Contract> contractsWithHttpUrls = contracts.map(this::convertLocalPathsToHttpUrls);
        System.out.println("Contracts with URLs: " + contractsWithHttpUrls.getContent().size() + " items");

        System.out.println("Contracts found: " + contracts.getContent().size());
        System.out.println("Total elements: " + contracts.getTotalElements());
        System.out.println("Total pages: " + contracts.getTotalPages());

        return ResponseEntity.ok(contractsWithHttpUrls);
    }

    // 获取用户收藏合同（分页、关键字、分类）
    @GetMapping("/favorites")
    public ResponseEntity<?> getUserFavorites(
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) String category) {
        try {
            if (!StpUtil.isLogin()) {
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(Map.of("error", "未登录"));
            }

            Integer userId = StpUtil.getLoginIdAsInt();
            System.out.println("【Favorites】用户ID: " + userId + ", 关键字: " + keyword + ", 分类: " + category);

            List<Contract> favorites = contractService.getUserFavorites(userId);
            System.out.println("【Favorites】获取到原始收藏列表，数量: " + favorites.size());

            // 添加搜索过滤逻辑
            if (keyword != null && !keyword.isEmpty()) {
                favorites = favorites.stream().filter(contract -> {
                    boolean keywordMatch =
                            (contract.getName() != null && contract.getName().contains(keyword)) ||
                                    (contract.getDescription() != null && contract.getDescription().contains(keyword));
                    return keywordMatch;
                }).collect(ArrayList::new, (list, item) -> list.add(item), (list1, list2) -> list1.addAll(list2));
                System.out.println("【Favorites】关键字过滤后数量: " + favorites.size());
            }

            if (category != null && !category.isEmpty()) {
                favorites = favorites.stream().filter(contract ->
                        contract.getCategory() != null && contract.getCategory().equals(category)
                ).collect(ArrayList::new, (list, item) -> list.add(item), (list1, list2) -> list1.addAll(list2));
                System.out.println("【Favorites】分类过滤后数量: " + favorites.size());
            }

            System.out.println("【Favorites】最终返回 " + favorites.size() + " 个合同");

            // 确保转换所有收藏合同的路径为HTTP URL
            List<Contract> favoritesWithHttpUrls = favorites.stream()
                    .map(this::convertLocalPathsToHttpUrls)
                    .collect(ArrayList::new, (list, item) -> list.add(item), (list1, list2) -> list1.addAll(list2));

            return ResponseEntity.ok(favoritesWithHttpUrls);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(Map.of("error", "服务器错误"));
        }
    }


    // 辅助方法：转换本地路径为HTTP URL
    private Contract convertLocalPathsToHttpUrls(Contract contract) {
        if (contract.getImgUrl() != null && !contract.getImgUrl().isEmpty()) {
            contract.setImgUrl(fileServerUrl + "/" + contract.getId() + "/preview");
        } else if (contract.getFileId() != null && !contract.getFileId().isEmpty()) {
            contract.setImgUrl(fileServerUrl + "/" + contract.getId() + "/preview");
        }

        if (contract.getPdfUrl() != null && !contract.getPdfUrl().isEmpty()) {
            contract.setPdfUrl(fileServerUrl + "/" + contract.getId() + "/download");
        }

        return contract;
    }

    // 上传PDF文件
    @PostMapping("/upload")
    public ResponseEntity<Contract> uploadContractWithFile(
            @RequestParam("name") String name,
            @RequestParam("category") String category,
            @RequestParam("description") String description,
            @RequestParam("file") MultipartFile file) {

        try {
            Contract contract = new Contract();
            contract.setName(name);
            contract.setCategory(category);
            contract.setDescription(description);
            contract.setUploadTime(LocalDateTime.now());

            Contract savedContract = contractService.createContract(contract);
            Contract contractWithFile = contractService.handleFileUpload(savedContract.getId(), file);

            return new ResponseEntity<>(contractWithFile, HttpStatus.CREATED);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

    // 编辑合同时上传文件
    @PutMapping("/{id}/upload")
    public ResponseEntity<Contract> updateContractWithFile(
            @PathVariable Integer id,
            @RequestParam("file") MultipartFile file) {

        Contract updatedContract = contractService.handleFileUpload(id, file);
        return ResponseEntity.ok(updatedContract);
    }

    // 单文件上传
    @PostMapping("/upload-file")
    public ResponseEntity<Map<String, String>> uploadSingleFile(
            @RequestParam("file") MultipartFile file) {
        try {
            if (file.isEmpty()) {
                throw new BusinessException("文件不能为空");
            }

            String fileName = contractService.saveFile(file);
            Map<String, String> response = new HashMap<>();
            response.put("fileName", fileName);
            response.put("fileId", fileName);
            response.put("message", "文件上传成功");

            return ResponseEntity.ok(response);
        } catch (BusinessException e) {
            Map<String, String> errorResponse = new HashMap<>();
            errorResponse.put("error", e.getMessage());
            return ResponseEntity.badRequest().body(errorResponse);
        } catch (Exception e) {
            Map<String, String> errorResponse = new HashMap<>();
            errorResponse.put("error", "文件上传失败：" + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResponse);
        }
    }

    // 下载PDF
    @GetMapping("/{id}/download")
    public ResponseEntity<byte[]> downloadPdf(@PathVariable Integer id) {
        try {
            contractService.increaseDownloadCount(id);
            byte[] pdfBytes = contractService.downloadPdf(id);

            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_PDF);
            headers.setContentDispositionFormData("attachment", "contract_" + id + ".pdf");
            headers.setContentLength(pdfBytes.length);

            return new ResponseEntity<>(pdfBytes, headers, HttpStatus.OK);
        } catch (BusinessException e) {
            System.err.println("业务异常: " + e.getMessage());
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

    // 预览图片
    @GetMapping("/{id}/preview")
    public ResponseEntity<byte[]> previewImage(@PathVariable Integer id) {
        try {
            contractService.increasePreviewCount(id);
            byte[] imageBytes = contractService.previewImage(id);

            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.IMAGE_PNG);
            if (imageBytes != null) {
                headers.setContentLength(imageBytes.length);
            }

            return new ResponseEntity<>(imageBytes, headers, HttpStatus.OK);
        } catch (BusinessException e) {
            System.err.println("预览图业务异常: " + e.getMessage());
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
        } catch (Exception e) {
            System.err.println("预览图系统异常: " + e.getMessage());
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

    // 增加下载次数
    @PostMapping("/{id}/downloadCount")
    public ResponseEntity<Map<String, Integer>> increaseDownloadCount(@PathVariable Integer id) {
        try {
            int newCount = contractService.increaseDownloadCount(id);
            Map<String, Integer> response = new HashMap<>();
            response.put("downloadCount", newCount);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

    // 增加预览次数
    @PostMapping("/{id}/previewCount")
    public ResponseEntity<Map<String, Integer>> increasePreviewCount(@PathVariable Integer id) {
        try {
            int newCount = contractService.increasePreviewCount(id);
            Map<String, Integer> response = new HashMap<>();
            response.put("previewCount", newCount);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

    // 获取所有分类
    @GetMapping("/categories")
    public ResponseEntity<Map<String, Object>> getAllCategories() {
        Map<String, Object> response = new HashMap<>();
        response.put("categories", new String[]{"销售合同", "采购合同", "劳动合同", "服务合同", "租赁合同"});
        return ResponseEntity.ok(response);
    }

    // 获取统计信息
    @GetMapping("/stats")
    public ResponseEntity<ContractService.ContractStats> getContractStats() {
        return ResponseEntity.ok(contractService.getContractStats());
    }

    // ✅ 收藏/取消收藏合同
    @PostMapping("/{id}/favorite")
    public ResponseEntity<Map<String, Object>> toggleFavorite(@PathVariable Integer id, @RequestBody Map<String, Boolean> payload) {
        try {
            Boolean favorite = payload.get("favorite");
            Integer userId = StpUtil.getLoginIdAsInt();
            System.out.println("toggleFavorite called: id=" + id + ", userId=" + userId + ", favorite=" + favorite);

            Contract updatedContract = contractService.toggleFavorite(id, userId, favorite);
            System.out.println("Updated contract favorite count: " + updatedContract.getFavoriteCount());

            Map<String, Object> response = new HashMap<>();
            response.put("favoriteCount", updatedContract.getFavoriteCount());
            response.put("isFavorite", favorite);

            System.out.println("Returning response: favoriteCount=" + updatedContract.getFavoriteCount() + ", isFavorite=" + favorite);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            e.printStackTrace();
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("error", "操作失败：" + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResponse);
        }
    }
}